#include "utils.h"
#include "generaldef.h"

#include <cstdio>
#include <cstring>
#include <cstdlib>

namespace fdutils{	// utilities for files and directories.
	void addslash(char path[]){
		if(path[strlen(path)-1]!='/'){
			path[strlen(path)]='/';
			path[strlen(path)]=0;
		}
	}

	void getname(char name[], char path[]){
		memset(name,0,NAME_LEN);
		for(int i=strlen(path)-1; i>=0; i--){
			if(path[i]=='/'){
				strncpy(name,path+i+1,strlen(path)-i-1);
				break;
			}
		}
		if(!name[0] && path[strlen(path)-1]!='/') strncpy(name,path,NAME_LEN);
	}

	void gettype(char type[], char barename[], char name[]){
		memset(type,0,NAME_LEN);
		memset(barename,0,NAME_LEN);
		for(int i=strlen(name)-1; i>=0; i--){
			if(name[i]=='.'){
				strncpy(type,name+i+1,strlen(name)-i-1);
				strncpy(barename,name,i);
				break;
			}
		}
		if(type[0]==0 && name[strlen(name)-1]!='.')
			strncpy(type,name,NAME_LEN);
	}

	void getdirpath(char dirpath[], char path[]){
		memset(dirpath,0,sizeof(dirpath));
		for(int i=strlen(path)-1; i>=0; i--){
			if(path[i]=='/'){
				strncpy(dirpath,path,i);
				break;
			}
		}
		if(!dirpath[0]){
			dirpath[0]='.';
			dirpath[1]='\0';
		}
	}

	void relate(char target[], const char subobj[], const char parent[]){
		static char buffer[PATH_LEN];
		strcpy(buffer, parent);
		if(parent[strlen(parent)-1] && parent[strlen(parent)-1]!='/') strcat(buffer, "/");
		strcat(buffer, subobj);
		strcpy(target, buffer);
	}
}

namespace progutils{
	void error(const char *msg){
		printf("%s",msg);
		exit(1);
	}

	void sigint(){
		error("SIGINT caught, exitting....\n");
	}
}

namespace strutils{
	void putfront(char *target, const char *src){
		memmove(target,target+strlen(src),strlen(src));
		memcpy(target,src,strlen(src));
	}
}


